package api;

import Dao.User;
import Dao.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Home-pc
 * Date: 2023-11-02
 * Time: 16:59
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    //1.从请求中获取用户名和密码
        //    给请求对象设置字符集, 保证说请求中的 username 或者 password 是中文, 也能正确处理.
        req.setCharacterEncoding("utf8");
        String username=req.getParameter("username");
        String password=req.getParameter("password");
        if(username==null || password==null || "".equals(username) || "".equals(password)){
            //这是用户名和密码有误
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("username or password is empty");
            return;
        }
        //2.从数据库的数据进行验证，看用户名和密码是否匹配
        //通过用户名查询信息
        UserDao userDao=new UserDao();
        User user=userDao.getUserByName(username);
        if(user==null){
            //当前提交的用户名密码错误
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("username or password is wrong");
            return;
        }
        if(!password.equals(user.getPassword())){
            //当前提交的用户名密码错误
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("username or password is wrong");
            return;
        }
        //3创建会话
        HttpSession session= req.getSession(true);
        // 把当前登录的用户信息保存到 session 中, 方便后续进行获取.
        session.setAttribute("user",user);
        //4跳转到博客列表页
        resp.sendRedirect("blog_list.html");
    }

    //使用这个方法来检测当前的登录状态，根据是否登录，返回给前端不同的状态码，供前端使用
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //根据上面，我们建立了会话为依据
        HttpSession session= req.getSession(false);
        if(session==null){
            //未登录，返回前端
            resp.setStatus(403);
            return;
        }
        //不仅仅要看session是否存在，还要看上述中存储的用户信息是否存在
        User user= (User) session.getAttribute("user");
        if(user==null){
            //未登录，返回前端
            resp.setStatus(403);
            return;
        }
        //表示已经登陆
        resp.setStatus(200);
    }
}
